#include "DataSvrClient.h"

LoggerPtr DataSvrClientGroup::_logger = Logger::getLogger("DataSvrClientGroup");

int DataSvrClientGroup::init(CnfSvrClient * csc) {
	_csc = csc;
	pthread_mutex_init(&_mutex, NULL);
	LOG4CXX_INFO(_logger, __FUNCTION__ << ", ok!");
	return 1;
}

DataSvrClient * DataSvrClientGroup::get_data_svr_client(int ds_id) {
	if (ds_id < 0) {
		LOG4CXX_ERROR(_logger, __FUNCTION__ << ", invalid args");
		return NULL;
	}
	DataSvrClient * client;
	pthread_mutex_lock(&_mutex);
	map<int, DataSvrClient *>::const_iterator iter = _clients.find(ds_id);
	if (_clients.end() != iter) {
		client = iter->second;
		pthread_mutex_unlock(&_mutex);
		return client;
	}
	list<DS_CNF> l_ds;
	int ret = _csc->get_all_ds_cnf(l_ds);
	if (ret < 0) {
		pthread_mutex_unlock(&_mutex);
		LOG4CXX_ERROR(_logger, __FUNCTION__ << ", could not get all ds cnf ret:" << ret);
		return NULL;
	}
	for (list<DS_CNF>::const_iterator iter = l_ds.begin(); l_ds.end() != iter; iter++) {
		if (iter->id == ds_id) {
			client = new DataSvrClient;
			ret = client->init(iter->ip.c_str(), iter->port, iter->client_conn_pool_size, \
				iter->socket_conn_timeout, iter->socket_send_timeout, iter->socket_recv_timeout, \
				iter->socket_max_response_size, ds_id);
			if (ret < 0) {
				pthread_mutex_unlock(&_mutex);
				delete client;
				LOG4CXX_ERROR(_logger, __FUNCTION__ << ", data svr client init err, ret:" << ret);
				return NULL;
			}
			_clients.insert(map<int, DataSvrClient *>::value_type(ds_id, client));
			pthread_mutex_unlock(&_mutex);
			LOG4CXX_INFO(_logger, __FUNCTION__ << ", insert ds client to client group, svr ip:" << iter->ip << \
					", port:" << iter->port);
			return client;
		}
	}
	pthread_mutex_unlock(&_mutex);
	LOG4CXX_ERROR(_logger, __FUNCTION__ << ", could not find ds id:" << ds_id << " in all data svrs");
	return NULL;
}
